package com.xing.asm.simple;

import com.xing.asm.simple2.MethodWriter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class MyAsm1
{

    public static void premain(String agentArgs, Instrumentation _inst)
    {
        _inst.addTransformer(new ClassFileTransformer()
        {
            public byte[] transform(ClassLoader loader, String className,
                                    Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain,
                                    byte[] classfileBuffer) throws IllegalClassFormatException {

                if(className.contains("Foo"))
                {
                    ClassReader cr = new ClassReader(classfileBuffer);
                    ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
                    ClassVisitor cv = new MethodWriter(cw);
                    cr.accept(cv, 0);
                    return cw.toByteArray();
                }
                return null;
            }
        });
    }

}
